import { useState, useEffect, useRef } from 'react';
import { Search, Menu, X } from 'lucide-react';
import { useSearch } from '../lib/search';

export function Navbar() {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [isSearchOpen, setIsSearchOpen] = useState(false);
  const { searchQuery, setSearchQuery, searchResults } = useSearch();
  const searchRef = useRef<HTMLDivElement>(null);

  // 点击外部关闭搜索框
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (searchRef.current && !searchRef.current.contains(event.target as Node)) {
        setIsSearchOpen(false);
        setSearchQuery('');
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [setSearchQuery]);

  const handleSearchToggle = () => {
    setIsSearchOpen(!isSearchOpen);
    if (!isSearchOpen) {
      setTimeout(() => {
        const searchInput = document.getElementById('search-input');
        if (searchInput) {
          searchInput.focus();
        }
      }, 100);
    } else {
      setSearchQuery('');
    }
  };

  const handleSearchItemClick = () => {
    setIsSearchOpen(false);
    setSearchQuery('');
    setIsMenuOpen(false);
  };
  return <header className="w-full py-6 px-4 md:px-8 border-b border-[#1a3a5c]">
      <div className="container mx-auto">
        <div className="flex items-center justify-between">
          <a href="/" className="flex items-center space-x-3 group">
            <div className="relative">
              <div className="w-10 h-10 rounded-lg bg-[#06d6a0] bg-opacity-10 flex items-center justify-center group-hover:bg-opacity-20 transition-all duration-300">
                <svg width="24" height="24" viewBox="0 0 36 36" fill="none">
                  <path d="M8 6 Q18 12 8 18 Q18 24 8 30" stroke="#06d6a0" strokeWidth="2.5" fill="none" strokeLinecap="round"/>
                  <path d="M28 6 Q18 12 28 18 Q18 24 28 30" stroke="#06d6a0" strokeWidth="2.5" fill="none" strokeLinecap="round"/>
                  <line x1="12" y1="12" x2="24" y2="12" stroke="#06d6a0" strokeWidth="1.5" opacity="0.7"/>
                  <line x1="12" y1="24" x2="24" y2="24" stroke="#06d6a0" strokeWidth="1.5" opacity="0.7"/>
                  <circle cx="18" cy="18" r="6" fill="#0a2540" opacity="0.9"/>
                  <path d="M15 18 L21 18 M18 15 L18 21" stroke="#06d6a0" strokeWidth="2" strokeLinecap="round"/>
                </svg>
              </div>
            </div>
            <div className="flex flex-col">
              <div className="text-xl font-bold tracking-tight">
                <span className="text-[#06d6a0]">Vita</span><span className="text-white">Incubator</span>
              </div>
              <div className="text-xs text-gray-400 font-medium tracking-widest hidden sm:block">
                WELLNESS INNOVATION
              </div>
            </div>
          </a>
          <div className="hidden md:flex items-center space-x-8">
            <nav className="flex items-center space-x-8">
              <a href="/" className="font-medium hover:text-[#06d6a0] transition-colors">
                Home
              </a>
              <a href="/reviews" className="font-medium hover:text-[#06d6a0] transition-colors">
                Reviews
              </a>
              <a href="/top-picks" className="font-medium hover:text-[#06d6a0] transition-colors">
                Top Picks
              </a>
              <a href="/guides" className="font-medium hover:text-[#06d6a0] transition-colors">
                Guides
              </a>
              <a href="/about" className="font-medium hover:text-[#06d6a0] transition-colors">
                About
              </a>
              <a href="/contact" className="font-medium hover:text-[#06d6a0] transition-colors">
                Contact
              </a>
            </nav>
            <div className="relative" ref={searchRef}>
              <button 
                aria-label="Search" 
                className="p-2 hover:text-[#06d6a0] transition-colors"
                onClick={handleSearchToggle}
              >
                <Search size={20} />
              </button>
              
              {/* Search Box */}
              {isSearchOpen && (
                <div className="absolute right-0 top-full mt-2 w-80 bg-[#061a2c] border border-[#1a3a5c] rounded-lg shadow-xl z-50">
                  <div className="p-4">
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={16} />
                      <input
                        id="search-input"
                        type="text"
                        placeholder="Search products, reviews, guides..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="w-full pl-10 pr-4 py-2 bg-[#0a2540] border border-[#1a3a5c] rounded-md text-white placeholder-gray-400 focus:outline-none focus:border-[#06d6a0]"
                      />
                    </div>
                    
                    {/* Search Results */}
                    {searchResults.length > 0 && (
                      <div 
                        className="mt-3 max-h-64 overflow-y-auto custom-scrollbar"
                        style={{
                          scrollbarWidth: 'thin',
                          scrollbarColor: '#1a3a5c #061a2c'
                        }}
                      >
                        {searchResults.map((item) => (
                          <a
                            key={item.id}
                            href={item.url}
                            onClick={handleSearchItemClick}
                            className="block p-3 hover:bg-[#0a2540] rounded-md transition-colors group"
                          >
                            <div className="flex items-start justify-between">
                              <div className="flex-1">
                                <div className="flex items-center gap-2 mb-1">
                                  <span className={`text-xs px-2 py-1 rounded ${
                                    item.type === 'review' 
                                      ? 'bg-[#06d6a0] text-[#0a2540]' 
                                      : item.type === 'guide'
                                      ? 'bg-[#f8961e] text-[#0a2540]'
                                      : 'bg-[#1a3a5c] text-white'
                                  }`}>
                                    {item.type === 'review' ? 'Review' : item.type === 'guide' ? 'Guide' : 'Article'}
                                  </span>
                                  <span className="text-xs text-gray-400">{item.category}</span>
                                </div>
                                <h4 className="text-sm font-medium text-white group-hover:text-[#06d6a0] transition-colors">
                                  {item.title}
                                </h4>
                                <p className="text-xs text-gray-400 mt-1 overflow-hidden text-ellipsis whitespace-nowrap">
                                  {item.description}
                                </p>
                              </div>
                            </div>
                          </a>
                        ))}
                      </div>
                    )}
                    
                    {searchQuery && searchResults.length === 0 && (
                      <div className="mt-3 p-3 text-center text-gray-400 text-sm">
                        No results found
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
          <button className="md:hidden p-2" onClick={() => setIsMenuOpen(!isMenuOpen)} aria-label="Toggle menu">
            {isMenuOpen ? <X size={24} /> : <Menu size={24} />}
          </button>
        </div>
        {/* Mobile menu */}
        {isMenuOpen && <div className="md:hidden pt-4 pb-2">
            <nav className="flex flex-col space-y-4">
              <a href="/" className="font-medium py-2 hover:text-[#06d6a0] transition-colors">
                Home
              </a>
              <a href="/reviews" className="font-medium py-2 hover:text-[#06d6a0] transition-colors">
                Reviews
              </a>
              <a href="/top-picks" className="font-medium py-2 hover:text-[#06d6a0] transition-colors">
                Top Picks
              </a>
              <a href="/guides" className="font-medium py-2 hover:text-[#06d6a0] transition-colors">
                Guides
              </a>
              <a href="/about" className="font-medium py-2 hover:text-[#06d6a0] transition-colors">
                About
              </a>
              <a href="/contact" className="font-medium py-2 hover:text-[#06d6a0] transition-colors">
                Contact
              </a>
              <button 
                aria-label="Search" 
                className="flex items-center py-2 hover:text-[#06d6a0] transition-colors"
                onClick={handleSearchToggle}
              >
                <Search size={20} className="mr-2" /> Search
              </button>
              
              {/* Mobile Search Box */}
              {isSearchOpen && (
                <div className="mt-4 p-4 bg-[#061a2c] border border-[#1a3a5c] rounded-lg">
                  <div className="relative mb-3">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={16} />
                    <input
                      type="text"
                      placeholder="Search products, reviews, guides..."
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      className="w-full pl-10 pr-4 py-2 bg-[#0a2540] border border-[#1a3a5c] rounded-md text-white placeholder-gray-400 focus:outline-none focus:border-[#06d6a0]"
                    />
                  </div>
                  
                  {/* Mobile Search Results */}
                  {searchResults.length > 0 && (
                    <div 
                      className="max-h-48 overflow-y-auto space-y-2 custom-scrollbar"
                      style={{
                        scrollbarWidth: 'thin',
                        scrollbarColor: '#1a3a5c #061a2c'
                      }}
                    >
                      {searchResults.map((item) => (
                        <a
                          key={item.id}
                          href={item.url}
                          onClick={handleSearchItemClick}
                          className="block p-2 hover:bg-[#0a2540] rounded-md transition-colors group"
                        >
                          <div className="flex items-center gap-2 mb-1">
                            <span className={`text-xs px-2 py-1 rounded ${
                              item.type === 'review' 
                                ? 'bg-[#06d6a0] text-[#0a2540]' 
                                : item.type === 'guide'
                                ? 'bg-[#f8961e] text-[#0a2540]'
                                : 'bg-[#1a3a5c] text-white'
                            }`}>
                              {item.type === 'review' ? 'Review' : item.type === 'guide' ? 'Guide' : 'Article'}
                            </span>
                            <span className="text-xs text-gray-400">{item.category}</span>
                          </div>
                          <h4 className="text-sm font-medium text-white group-hover:text-[#06d6a0] transition-colors">
                            {item.title}
                          </h4>
                          <p className="text-xs text-gray-400 mt-1 overflow-hidden text-ellipsis whitespace-nowrap">
                            {item.description}
                          </p>
                        </a>
                      ))}
                    </div>
                  )}
                  
                  {searchQuery && searchResults.length === 0 && (
                    <div className="p-2 text-center text-gray-400 text-sm">
                      No results found
                    </div>
                  )}
                </div>
              )}
            </nav>
          </div>}
      </div>
    </header>;
}